#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
This module contains all utilities for manipulating strings. It's here
to maintain the compatibility of Python2 and Python3 strings. With this
module, we don't need 2to3 tool to convert codebase.
"""


__all__ = [ 'isunicode', 'isbyte', 'u_', 'b_', 'try2int' ]

def isunicode(inputstr):
    """ Check if input string is unicode."""
    return type(inputstr) is type(''.encode().decode())

def isbyte(inputstr):
    """ Check if input string is multibyte string. """
    return type(inputstr) is type(''.encode())

def u_(inputstr, encoding = 'utf-8'):
    """
    _u(inputstr, encoding = 'utf-8')
    Convert input string to Unicode.
    * If input string is multibyte, it will be converted to Unicode.
    * If input string is already Unicode, no conversion will happen.
    * If the string fails to convert, a UnicodeDecodeError will be raised.
    * For other cases, an InvalidParameterError will be raised.
    """
    if isunicode(inputstr):
        return inputstr
    elif isbyte(inputstr):
        return inputstr.decode(encoding)
    else:
        raise TypeError('inputstr', "type = {0}".format(type(inputstr)))

def b_(inputstr, encoding = 'utf-8'):
    """
    b_(inputstr, encoding = 'utf-8')
    Convert input string to multi-byte.
    * If input string is Unicode, it will be converted to to multibyte.
    * If input string is already multibyte, no conversion will happen.
    * If the string fails to convert, a UnicodeEncodeError will be raised.
    * For other cases, an InvalidParameterError will be raised.
    """
    if isbyte(inputstr):
        return inputstr
    elif isunicode(inputstr):
        return inputstr.encode(encoding)
    else:
        raise TypeError('inputstr', "type = {0}".format(type(inputstr)))

def try2int(strval):
    try:
        intval = int(strval)
        return intval
    except:
        return None

# vim:tw=78:et:sw=4
